<?php
namespace Core\Handler;
use Core\Base;
use Core\Loader;
use Core\Once;
use Core\Server;

class Http extends Base {

    function setServerHandler(\swoole_http_server $server) {

    }

    function handle(\swoole_http_request $request,\swoole_http_response $response) {
        Once::$REQUEST = &$request;
        Once::$RESPONSE = &$response;
        $host = $request->header['host'];
        if(!isset(Server::Instance()->appConfig['domains'][$host])) {
            $response->status(404);
            return $response->end('no such host:'.$host);
        }
        Once::$APP_PATH =  Server::Instance()->appConfig['domains'][$host][1];
        Once::$APP_PARAM = Server::Instance()->appConfig['domains'][$host][2];
        Loader::Instance()->paths[Server::Instance()->appConfig['domains'][$host][0]] = Once::$APP_PATH;

        $controllerArr = ['Index'];
        $action = 'index';
        $uris = explode('/',trim($request->server['request_uri'],'/'));
        $uris_len = count($uris);
        switch ($uris_len) {
            case 0:
                break;
            case 1:
                if($uris[0] != '') {
                    $controllerArr[0] = ucfirst($uris[0]);
                }
                break;
            default:
                $action = array_pop($uris);
                $controllerArr = $uris;
        }
        $className = Server::Instance()->appConfig['domains'][$host][0].'Controller\\'.implode('\\',$controllerArr);
        try {
            /**
             * @var $controller \Core\Controller\Base
             */
            $controller = $className::Instance([
                'request' => &$request,
                'response' => &$response,
                'name' => implode('/',$controllerArr),
                'action' => $action,
            ]);
            Once::$Controller = &$controller;
            if($controller->break) {

            }else {
                $action = $action.'Action';
                $ret = $controller->$action();
                if($controller->break) {

                }else {
                    if(is_string($ret)) {
                        $response->end($ret);
                    }else if($ret === false) {
                        $response->end();
                    }else {
                        $response->end($controller->render());
                    }
                }
            }
       }catch (\Error $e) {
            $response->status(404);
            $response->end('ERROR:'.$e->getFile().':'.$e->getLine().' '.$e->getMessage().'  trace:'.$e->getTraceAsString());
        }catch (\Exception $e) {
            $response->status(404);
            $response->end('EXCEPTION:'.$e->getFile().':'.$e->getLine().' '.$e->getMessage().'  trace:'.$e->getTraceAsString());
        }
        Once::close();
        Base::FreeObj();
    }
}